from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from django.db import transaction
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from .ser import *
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import User


class LoginAPIView(APIView):
    # 后台登录接口
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        try:
            user = User.objects.get(username=username, password=password)
        except Exception as e:
            return Response({'code': '999', 'msg': '账号密码错误'}, status=401)

        # 判断是否管理员
        if user.is_admin:
            return Response({'code': '0', 'msg': '欢迎' + user.username, 'data': {
                'uid': user.id,
                'username': user.username,
                'is_admin': user.is_admin,
            }})
            pass
        else:
            Response({'code': '999', 'msg': '不是管理员不能登录后台'}, status=401)
            pass


class RegisterAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        if all([username, password]):
            pass
        else:
            return Response({'code': '999', 'msg': '参数不足'})

        count_user = User.objects.filter(username=username).count()

        if count_user > 0:
            return Response({'code': '999', 'msg': '用户名已存在'})
        else:
            User.objects.create(username=username, password=password)
            return Response({'code': '0', 'msg': '注册成功'})



class RechargeAPIView(APIView):
    @transaction.atomic
    def post(self, request):
        # 充值
        pass
        username = request.data.get('username')
        money = int(request.data.get('money'))

        if all([username, money]):
            pass
        else:
            return Response({'code': '999', 'msg': '缺少参数'})

        # 0. 送多少钱
        sum = 0  # 优惠总金额
        money2 = money  # 变化的总额
        all_discount = Discount.objects.all().order_by('-give_money')
        """
        money = 1234
        all_discount = [500,150| 200,50| 100|20]
        
        1234%500  =>  234
        2
        234
        """

        for dis in all_discount:
            num = money2 // dis.money  # 求出优惠次数
            give_money = num * dis.give_money  # 求出优惠金额
            sum += give_money  # 保存优惠金额
            money2 -= num * dis.money
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return Response({'code': '999', 'msg': '没有此用户'})
        # 1. 要改用户余额,

        if money >= 200:
            # 设置vip
            user.is_vip = True

        user.balance = user.balance + money + sum
        user.save()

        # 2. 要增加充值记录
        MoneyRecord.objects.create(user=user, money=money, give_money=sum)

        return Response({'code': '0', 'msg': '充值成功'})


class MoneyRecordViewSet(viewsets.ModelViewSet):
    queryset = MoneyRecord.objects.all()
    serializer_class = MoneyRecordSerializer


class DiscountViewSet(viewsets.ModelViewSet):
    queryset = Discount.objects.all()
    serializer_class = DiscountSerializer
